import Msgpg from './Msgpg.js';
import * as bfun from '../../core/fbyte.js';
import * as fun from '../../core/fun.js';
/**
 * 
 客服专用websocket 组件
 *  用例 :
 *  var hkf = new Hwskf("localhost:8080/hjsp/ws/a/1", function(e,o) {
      console.log(e)
    })
 */
export default class Hwskf{
	
	constructor(服务路径, 收到消息回调, 连接回调, 断开回调)  {
		// 0 系统消息 1用户消息 2 用户指令
		this.socket = null;
		this.messageNum = 0; //收到消息数
		this.socketConnectedEnable = true;		
		this._onReceivePg = 收到消息回调;
		this._onOpen = 连接回调;
		this._onClose = 断开回调;
		if (服务路径==null||服务路径=='')return null;
		
		if(服务路径.startsWith('ws://'))
			this._url = 服务路径;
		else
			this._url = "ws://" + 服务路径;
		console.log(this._url, serverurl)
	}
	
	
	//ws://localhost:8080/hjsp/wsadmin

	connect() {
		let that=this;
		if ('WebSocket' in window) {
			that.socket = new window.WebSocket(that._url);
		} else {
			if ('MozWebSocket' in window) {
				that.socket = new window.MozWebSocket(that._url);
			} else {
				console.log('当前浏览器 不支持 websocket')
				return;
			}
		}
		//收到消息
		that.socket.onmessage = function(evt) {
			that.messageNum++;
			if (that._onReceivePg && evt.data) {
				let data = evt.data;
				while (true) {
					let pg = new Msgpg();
					if (pg.ini(data)) {
						that._onReceivePg(pg, that);
						data = data.slice(pg.length());
					} else {
						return;
					}
				}
			}
		};

		//连接成功
		that.socket.onopen = function(e) {			
			console.log("连接开启!",e)
			if (that._onOpen)
				that._onOpen(e,that);		
		};
		//连接成功
		that.socket.onclose = function(e) {
			if (that._onClose)
				that._onClose(e);
			console.log("连接关闭!")
		};
		// that.timer = setInterval(function() {
		// 	if (that.socketConnectedEnable) {
		// 		//console.log("ping");
		// 		that.send("hi");
		// 	}
		// }, 180000);
	}
	/**
	 * 私有函数不建议直接使用  因为 已经使用了标准协议包对象 MsgPg
	 * @param {Object} bytes
	 */
	send(bytes) {	
		if (this.me ==null) return ;
		if (this.socket && this.socket.readyState == 1) {	
			this.socket.send(bytes);
		} else {
			this.socket = null;
			console.log("连接已经关闭,重新连接");
			setTimeout(this.connect, 1000);
		}
	}
	
	/**
	 * 适用于文本内容
	 */
	sendStr(发送人,接收人,主题,文本,message) {
		if (fun._IS.isEmptyString(发送人)) return;
		if (fun._IS.isEmptyString(文本)&&message==null) return;
		let pg=new MsgPg(发送人,接收人,主题,文本,bfun.strToUtf8Array(message));
		this.sendPg (pg);
	}
	/**
	 * 适用于图片等内容
	 */
	sendBytes(发送人,接收人,主题,文本,message) {
		if (fun._IS.isEmptyString(发送人)) return;
		if (fun._IS.isEmptyString(文本)&&message==null) return;
		let pg=new MsgPg(发送人,接收人,主题,文本,message);
		this.sendPg (pg);
	}
	/**
	 * @param {Msgpg} pg
	 */
	sendPg(pg) {
		this.send(pg.toSendBytes());
	}
	

	//保持连接的方式 每隔100s  ping一下主机 如果断开重连
	
	//
	close() {
		console.log("关闭??")
		clearTimeout(that.timer);
		that.socket.close();
	}

};
